//
//  ContactController.m
//  OCDemo
//
//  Created by BH on 15/10/22.
//  Copyright © 2015年 baohan. All rights reserved.
//

#import "ContactController2.h"
#import <Masonry/Masonry.h>
#import "PPTranslator.h"
#import "GlobalDefine.h"

@interface ContactController2 ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *dataArr;
    NSMutableArray *headerArr;
    NSDictionary *dataDic;
    
    UITextField *textF;
}

@property(nonatomic,strong)UITableView *table;

@end

@implementation ContactController2

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addView];
    [self getData];
    [self addAlphaBetButton];
}

-(void)addView
{
    textF = [[UITextField alloc] init];
    textF.placeholder = @"搜索";
    textF.backgroundColor = [UIColor lightGrayColor];
    [textF addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    textF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:textF];
    
    _table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _table.dataSource = self;
    _table.delegate = self;
    [self.view addSubview:_table];
    
    [textF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.right.equalTo(self.view).offset(-15);
        make.top.equalTo(self.view).offset(5+64);
        make.height.equalTo(@40);
    }];
    
    [_table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textF.mas_bottom).offset(5);
        make.left.right.bottom.equalTo(self.view);
    }];
}

-(void)textChange:(UITextField *)sender
{
    if (![sender.text isEqualToString:@""]) {
        if (([sender.text characterAtIndex:0] > 64 && [sender.text characterAtIndex:0] < 91) || ([sender.text characterAtIndex:0] > 96 && [sender.text characterAtIndex:0] < 123)) {
            //字母转换为大写
            NSString *str = [[sender.text substringToIndex:1] uppercaseString];
            [self searchDataWithAlphabet:str flag:1];
        }else{
            
            [self searchDataWithAlphabet:[sender.text substringToIndex:1] flag:2];
        }
    }else{
        
        [self viewDidLoad];
    }
}

-(void)searchDataWithAlphabet:(NSString *)string flag:(NSInteger)flag
{
    BOOL hadAlp = false;
    NSMutableArray *muAry = [NSMutableArray array];
    
    if (flag == 1) {
        NSArray *allKeys = [dataDic allKeys];
        for (int i = 0; i<allKeys.count; i++) {
            if ([allKeys[i] isEqualToString:string]) {
                NSArray *newAry = [dataDic objectForKey:string];
                hadAlp = true;
                [muAry addObject:newAry];
            }
        }
    }else{
        
        for (int i = 0; i<dataArr.count; i++) {
            for (int j = 0; j<[dataArr[i] count]; j++) {
                if ([[dataArr[i][j] substringToIndex:1] isEqualToString:string]) {
                    NSArray *newAry = [NSArray arrayWithObject:dataArr[i][j]];
                    if (!hadAlp) {
                        hadAlp = true;
                        muAry = [NSMutableArray array];
                    }
                    [muAry addObject:newAry];
                }
            }
        }
    }
    
    if (!hadAlp) {
        dataArr = nil;
    }else{
        dataArr = muAry;
    }
    
    UITableView *searchtable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    searchtable.dataSource = self;
    searchtable.delegate = self;
    [self.view addSubview:searchtable];
    
    [searchtable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textF.mas_bottom).offset(5);
        make.left.right.bottom.equalTo(self.view);
    }];
}

-(void)getData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ContactList" ofType:@"plist"];
    NSArray *tempAry = [NSArray arrayWithContentsOfFile:path];
    
    NSMutableArray *pinyinArr = [NSMutableArray array];
    NSMutableArray *upStrArr = [NSMutableArray array];
    
    for (int i=0; i<tempAry.count; i++) {
        NSString *pinyin = [tempAry[i] translatorToPinYinFirstAscii];
        [pinyinArr addObject:pinyin];
        [upStrArr addObject:[pinyin substringWithRange:NSMakeRange(0, 1)]];
    }
    NSMutableDictionary *pinyinDic = [NSMutableDictionary dictionaryWithObjects:tempAry forKeys:pinyinArr];

    //对字母排序
    NSMutableArray *keyAscend = [NSMutableArray array];
    for (int i = 0; i<upStrArr.count; i++) {
        BOOL hasInserted = false;
        for (int j=0; j<keyAscend.count; j++) {
            if ([keyAscend[j] compare:upStrArr[i]] > 0) {
                hasInserted = true;
                [keyAscend insertObject:upStrArr[i] atIndex:j];
                break;
            }
        }
        if (!hasInserted) {
            [keyAscend addObject:upStrArr[i]];
        }
    }
    
    headerArr = [[NSMutableArray alloc] init];
    for (int i = 0; i<keyAscend.count; i++) {
        if ([headerArr containsObject:keyAscend[i]] == NO) {
            [headerArr addObject:keyAscend[i]];
        }
    }
    
    dataArr = [[NSMutableArray alloc] init];
    for (int i=0; i<headerArr.count; i++) {
        NSMutableArray *muAry = [NSMutableArray array];
        for (int j=0; j<pinyinArr.count; j++) {
            if ([[pinyinArr[j] substringWithRange:NSMakeRange(0, 1)] isEqualToString:headerArr[i]]) {
                [muAry addObject:[pinyinDic objectForKey:pinyinArr[j]]];
            }
        }
        [dataArr addObject:muAry];
    }
    
    dataDic = [NSDictionary dictionaryWithObjects:dataArr forKeys:headerArr];
    
}

//添加索引
-(void)addAlphaBetButton
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_W-30*SCREEN_W/375, 55*SCREEN_H/667*2, 30*SCREEN_W/375, SCREEN_H-55*SCREEN_H/667*2)];
    view.backgroundColor = [UIColor whiteColor];
    view.tag = 100;
    [self.view addSubview:view];
    
    float w = view.bounds.size.width;
    float h = view.bounds.size.height/[headerArr count];
    
    for (int i = 0; i<headerArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, h*i, w, h);
        [button setTitle:headerArr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(alphaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
}

//滚动到相对索引位置
-(void)alphaBtnClick:(UIButton *)sender
{
    NSIndexPath *scrollindex = [NSIndexPath indexPathForRow:0 inSection:[headerArr indexOfObject:sender.titleLabel.text]];
    [_table scrollToRowAtIndexPath:scrollindex atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - tableview datasource & delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _table) {
        return 10*SCREEN_H/667;
    }else{
        return 0;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArr[section] count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.contentView.backgroundColor = [UIColor whiteColor];
    cell.textLabel.textColor = [UIColor orangeColor];
    cell.textLabel.text = dataArr[indexPath.section][indexPath.row];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.f];
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20*SCREEN_W/375, 10*SCREEN_H/667)];
    lable.text = headerArr[section];
    lable.textColor = [UIColor blueColor];
    lable.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.f];
    
    return lable;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
